package sidecar

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"github.com/micro/go-micro/client"
	"github.com/micro/go-micro/client/selector"
	"github.com/micro/go-micro/registry"
	microHttp "github.com/micro/go-plugins/client/http"
	"github.com/micro/go-plugins/registry/etcdv3"
	"io/ioutil"
	"log"
	"net/http"
)

//其实这里就是为了构造这个json
//{ 	"id":"XXX", "jsonrpc":"2.0", "method":"Registry.Register",
//	"params": [{ "name":"XXX", "version":"X.X", "endpoints":[],
//				"nodes": [ { "address":"192.168.0.101", "id":"userservice-uuid", "port":8080 } ]
//	    	  }]
//}
type ServiceNode struct {
	Id      string //不能重复
	Port    int
	Address string
}

type Service struct {
	Name  string
	Nodes []*ServiceNode
}
type JSONRequest struct {
	JsonRpc string
	Method  string
	Params  []*Service
	Id      int
}

func NewService(name string) *Service {
	return &Service{Name: name, Nodes: make([]*ServiceNode, 0)}
}

func NewServiceNode(id string, port int, address string) *ServiceNode {
	return &ServiceNode{Id: id, Port: port, Address: address}
}
func (service *Service) AddNode(id string, port int, address string) {
	service.Nodes = append(service.Nodes, NewServiceNode(id, port, address))
}
func NewJsonRequest(service *Service, endpoint string) *JSONRequest {
	return &JSONRequest{JsonRpc: "2.0", Method: endpoint, Params: []*Service{service}, Id: 1}
}
func RegService(service *Service) error {
	return requestRegistry(NewJsonRequest(service, "Registry.Register"))
}

func DeRegService(service *Service) error {
	return requestRegistry(NewJsonRequest(service, "Registry.Deregister"))
}

var RegistryURI = "http://localhost:8000"

func requestRegistry(jr *JSONRequest) error {
	b, err := json.Marshal(jr)
	if err != nil {
		log.Fatal(err)
		return err
	}
	resp, err := http.Post(RegistryURI, "application/json", bytes.NewReader(b))
	if err != nil {
		log.Fatal(err)
		return err
	}
	defer resp.Body.Close()
	res, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
		return err
	}
	fmt.Println(string(res))
	return nil
}

// 调用注入到服务中心的外部五福
func callExternalService() {
	consulReg := etcdv3.NewRegistry(
		registry.Addrs("127.0.0.1:8500"),
	)
	microSelector := selector.NewSelector(
		selector.Registry(consulReg),          //注册中心
		selector.SetStrategy(selector.Random), //随机算法
	)
	microClient := microHttp.NewClient(
		client.Selector(microSelector),
		client.ContentType("application/json"),
	)
	req := microClient.NewRequest("prodService", "v1/prods", map[string]string{})
	var rsp map[string]interface{}
	err := microClient.Call(context.Background(), req, &rsp)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(rsp["data"])

}
